<?php

declare(strict_types=1);

namespace App\Controller;

use Swoole\Server;
use Swoole\Http\Request;
use Swoole\Websocket\Frame;
use Swoole\WebSocket\Server as WebSocketServer;
use Hyperf\WebSocketServer\Context;
use Hyperf\Contract\OnOpenInterface;
use Hyperf\Contract\OnCloseInterface;
use Hyperf\Contract\OnMessageInterface;

class WebSocketController implements OnMessageInterface, OnOpenInterface, OnCloseInterface
{
    public function onOpen($server, Request $request): void
    {
        $fd = $request->fd;
        $username = $request->cookie['username'] ?? "用户".$fd;
        Context::set('username', $username);
        $message = '"'.$username.'" 已上线';
        echo PHP_EOL . $message . PHP_EOL.PHP_EOL;
        $server->push($fd, $message);
    }

    public function onMessage($server, Frame $frame): void
    {
        $fd = $frame->fd;
        $username = Context::get('username');
        $message = '服务器收到 "'.$username.'" 的消息：' . PHP_EOL . $frame->data;
        echo PHP_EOL . $message . PHP_EOL.PHP_EOL;
        $server->push($fd, $message);
    }

    public function onClose($server, int $fd, int $reactorId): void
    {
        $username = Context::get('username');
        $message = '"'.$username.'" 已断开';
        echo PHP_EOL . $message . PHP_EOL.PHP_EOL;
    }
}
